﻿using System.Collections.Generic;
using System.IO;
using Core.Runtime;
using UnityEditor;
using UnityEditor.Build.Pipeline;
using UnityEditor.Build.Pipeline.Injector;
using UnityEditor.Build.Pipeline.Interfaces;
using UnityEngine;

namespace Core.Editor
{
    public class WriteAppVersion : IBuildTask
    {
        [InjectContext(ContextUsage.In)]
        private IBundleBuildConfigParam _configParam;

        public int Version => 1;

        public ReturnCode Run()
        {
            string outputPath = GetOutputPath();

            WriteToStreamingAssets(_configParam.Config.AppVersion, outputPath);
            Debug.Log($"成功生成客户端版本文件：{outputPath}");
            return ReturnCode.Success;
        }
        

        private string GetOutputPath()
        {
            string folder = Path.Combine(Application.streamingAssetsPath, "Updates");
            
            Directory.CreateDirectory(folder);
            return Path.Combine(folder, "AppVersion.txt");
        }

        private void WriteToStreamingAssets(string data, string path)
        {
            File.WriteAllText(path, data);
        }
    }
}
